<?php

namespace App\Libs\Company\SheetTemplateHandler\Aggregate;

use App\Libs\Company\SheetTemplateHandler\Manager;
use App\Models\SheetTemplate;
use Illuminate\Support\Facades\Log;

class Template226 extends AbstractTemplate
{
    public $dataStartRow = 3;

    public $dataEndRow = 12;

    protected $data = [
        '第1天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第2天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第3天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第4天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第5天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第6天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第7天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第8天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第9天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
        '第10天' => [1 => 0, 2 => 0, 3 => 0, 4 => 0.0],
    ];

    public function generateAbstract()
    {
        $this->renderHeader();
        $this->output['sheets']['sheet-01']['cellData']['0']['0'] = $this->createTitleCell($this->task->name);

        foreach ($this->task->subTasks as $subTask) {
            $handler = Manager::createReportHandler(SheetTemplate::find($this->task->sheet_template_id), $subTask);
            $data = $handler->getData();
            try {
                foreach ($this->data as $key => $value) {
                    if (empty($data[$key])) {
                        continue;
                    }
                    $this->data[$key][1] += (int) ($data[$key][1]['v'] ?? 0);
                    $this->data[$key][2] += (int) ($data[$key][2]['v'] ?? 0);
                    $this->data[$key][3] += (int) ($data[$key][3]['v'] ?? 0);
                    $this->data[$key][4] += (float) ($data[$key][4]['v'] ?? 0);
                }
            } catch (\Throwable $th) {
                Log::error('填报表异常 id:' . $subTask->id);
                throw $th;
            }
        }

        foreach ($this->data as $key => $value) {
            $this->output['sheets']['sheet-01']['cellData'][] = [
                ['v' => $key, 's' => 'CENTER'],
                ['v' => $value[1], 't' => 2],
                ['v' => $value[2], 't' => 2],
                ['v' => $value[3], 't' => 2],
                ['v' => round($value[4], 2), 't' => 2],
            ];
        }

        $this->renderFooter();
        return $this->output;
    }
}
